package cn.com.assistant.asr;

import org.json.JSONObject;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class VideoAnalyse {
    private static final String serverURL = "http://vop.baidu.com/server_api";
    private static String token = "";
//    private static final String testFileName = "C:\\Users\\小风风\\Desktop\\public\\16k.wav"; // 百度语音提供技术支持
    private static final String testFileName = "C:\\Users\\小风风\\Desktop\\录音4.wav"; // 百度语音提供技术支持
    //put your own params here
    // 下面3个值要填写自己申请的app对应的值
    private static final String apiKey = "e8OCHnjQG8nxcK6RZxOLBSCU";
    private static final String secretKey = "LNBMaRgFG6LilPTrDvGRq59APtl1gI4G";
    private static final String cuid = "LNBMaRgFG6LilPTrDvGRq59APtl1gI4G";

    public static void main(String[] args) throws Exception {
        getToken();
        method1();
        method2();
    }

    private static void getToken() throws Exception {
        String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +
                "&client_id=" + apiKey + "&client_secret=" + secretKey;
        HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();
        token = new JSONObject(printResponse(conn)).getString("access_token");
        System.out.println(token);
    }

    private static void method1() throws Exception {
        File pcmFile = new File(testFileName);
        System.out.println(pcmFile.exists());
        HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();

        // construct params
        JSONObject params = new JSONObject();
        params.put("format", "wav");
        params.put("rate", 16000);
        params.put("channel", "1");
        params.put("token", token);
        params.put("lan", "zh");
        params.put("cuid", cuid);
        params.put("len", pcmFile.length());
        params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));

        // add request header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        // send request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(params.toString());
        wr.flush();
        wr.close();

        printResponse(conn);
    }

    private static void method2() throws Exception {
        File pcmFile = new File(testFileName);
        HttpURLConnection conn = (HttpURLConnection) new URL(serverURL
                + "?cuid=" + cuid + "&token=" + token).openConnection();

        // add request header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "audio/pcm; rate=16000");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        // send request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(loadFile(pcmFile));
        wr.flush();
        wr.close();

        System.out.println(printResponse(conn));
    }

    private static String printResponse(HttpURLConnection conn) throws Exception {
        if (conn.getResponseCode() != 200) {
            // request error
            System.out.println("conn.getResponseCode() = " + conn.getResponseCode());
            return "";
        }
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        System.out.println(new JSONObject(response.toString()).toString(4));
        return response.toString();
    }

    private static byte[] loadFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        long length = file.length();
        byte[] bytes = new byte[(int) length];

        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        if (offset < bytes.length) {
            is.close();
            throw new IOException("Could not completely read file " + file.getName());
        }

        is.close();
        return bytes;
    }
//
//    public void adminGetVideoAudio(HttpServletResponse response, @RequestParam(value="fileId") String fileId) throws IOException {
//        FileInputStream input = null;
//        OutputStream output = null;
//        try{
//            //视频资源存储信息
//            FileManager fm =  Optional.ofNullable(fileService.selectById(fileId)).orElse(new FileManager());
//            File file = new File(fm.getFileUrl());
//            input = new FileInputStream(file);
//            ServletOutputStream out = response.getOutputStream();
//            output = new BufferedOutputStream(out);
//            //视屏
//            if("1".equals(String.valueOf(fm.getFileClass()))){
//                response.setHeader("Content-Type", "video/mp4");
//            }
//            //音频
//            if(fm.getFileClass().equals("2")){
//                response.setHeader("Content-Type", "audio/mpeg;charset=UTF-8");
//            }
//
//
////            int i = input.available();
////            byte[] bytes = new byte[i];
////            input.read(bytes);
//
//            byte[] buff = new byte[2048];
//            int bytesRead;
//            while (-1 != (bytesRead = input.read(buff, 0, buff.length))) {
//                output.write(buff, 0, bytesRead);
//
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            safeClose(input,output);
//        }finally {
//            safeClose(input,output);
//        }
//    }
//    public static void safeClose(FileInputStream input,OutputStream out) {
//        if (input != null) {
//            try {
//                input.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        if (out != null) {
//            try {
//                out.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
//}

}
